//5 functions of s-list

#include <iostream>
#include <stdlib.h>
using namespace std;

struct Elem
{
	Elem* next;
	int value;
};
struct List
{
	Elem* head;
	int len;
};
//I don't know how, but everything works fine without typedef
List* create_list()
{
	List* list = (List*) malloc (sizeof(List));
	list->head=0;
	list->len=0;
	return list;
}
Elem* create_elem(int val)
{
	Elem* elem = (Elem*) malloc (sizeof(Elem));
	elem->next=0;
	elem->value=val;
	return elem;
}
void append_to_begin(List* list, Elem* elem)
{
	elem->next=list->head;
	list->head=elem;
	list->len++;
}
void append_to_end(List* list, Elem* elem)
{
	Elem* d=list->head;
	while(d->next)		//go to tail
		d=d->next; 	//
	d->next=elem;
	list->len++;
}
void insert_after(List* list, Elem* elem, int x)
{
	Elem* d=list->head;
	for(int i=1;i<x;i++)	//go to x
		d=d->next;	//
	elem->next=d->next;
	d->next=elem;
	list->len++;
}
void print(List* list)
{
	Elem* d=list->head;
	for(int i=1;i<=(list->len);i++)
	{
		cout<<d->value<<" ";
		d=d->next;
	}
	cout<<endl;
}
void give_freedom(List* list)
{
	Elem* d=0;
	for(int i=1;i<=list->len;i++)
	{
		d=list->head->next;
		free(list->head);
		list->head=d;
	}
	free(list);
}
int main()
{
	List* spisok=create_list();

	Elem* d=create_elem(2);		//I want to put elements to tail of list
	append_to_begin(spisok, d);	//but I can not append_to_end while list is empty

	for(int i=4;i<=10000;i+=i)
	{
		Elem* d=create_elem(i);
		append_to_end(spisok, d);
	}

	print(spisok);
	cout<<"length1="<<spisok->len<<endl;	//I didn't make function for this

	d=create_elem(228);
	insert_after(spisok, d, 10);
	
	print(spisok);
	cout<<"length2="<<spisok->len<<endl;
	
	give_freedom(spisok);

	return 0;
}